<?php

namespace App\Services;

use App\Exceptions\InternalException;
use App\Models\Project;
use App\Models\Role;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class ProjectService
{
    public function get($search,$type = 'company'){
        $sql = Project::with('users')->withCount('users')->when($search, function ($query, $search) {
            return $query->where(function($query) use ($search) {
                $query->where('title','like', '%'.$search.'%');
            });
        });

        if($type == 'company'){
            $sql->where('company_id',Auth::user()->company_id);
        }
        return $sql;
    }

    public function getRoleUsers($id){
        $project = Project::with('users')->where('id',$id)->first();
        $users = $project->users;
        $users = $users->groupBy('role_id');
        $role_id = [];
        foreach ($users as $k => $v) {
            $role_id[] = $k;
        }
        $role = Role::select('id','name','status')->with('users')->whereIn('id',$role_id)->get();
        return $role;
    }

    public function insert($input){
        $res = [];
        foreach ($input as $k => $v) {
            if($v){
                $res[$k] = $v;
            }
        }
        try {
            $data = Project::create($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function update($input){
        $res = [];
        foreach ($input as $k => $v) {
            if($v){
                $res[$k] = $v;
            }
        }
        unset($res['id']);
        try {
            $data = Project::where('id',$input['id'])->update($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function projectBindUser($input){
        $user = Project::find($input['project_id']);
        $users = json_decode($input['users']);
        try {
            $user->users()->sync($users);
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }
    
}